<?php
//数据库操作类
namespace core;

use PDO;

class Query
{
    protected PDO $db;
    protected string $table;
    protected string $field = '*';
    protected int $limit = 10;
    //查询条件
    protected array $opt = [];

    //构造方法：创建连接对象PDO
    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    //设置数据表名称
    public function table(string $table): self
    {
        $this->table = $table;
        return $this;
    }

    //设置字段
    public function field(string $field = '*'): self
    {
        $this->field = $field;
        return $this;
    }

    //设置查询数量
    public function limit(int $num = 10): self
    {
        $this->limit = $num;
        $this->opt['limit'] = " LIMIT $num ";
        return $this;
    }

    /**
     * 设置分页
     * @param int $curr_page 当前页
     * @return void
     */
    public function page(int $curr_page = 1): self
    {
        $this->opt['offset'] = ' OFFSET ' . ($curr_page - 1) * $this->limit;
        return $this;
    }

    //排序
    public function order(string $field, string $order = 'DESC'): self
    {
        $this->opt['order'] = " ORDER BY $field $order ";
        return $this;
    }
    // 查询条件
    public function where(string $where = ''): self
    {
        $this->opt['where'] = " WHERE $where";
        return $this;
    }
    //获取全部记录
    public function select(): array
    {
        $sql = 'SELECT ' . $this->field . ' FROM ' . $this->table;
        $sql .= $this->opt['order'] ?? null;
        $sql .= $this->opt['limit'] ?? null;
        $sql .= $this->opt['offset'] ?? null;
        $sql .= ";";
        //获取预处理
        $stmt = $this->db->prepare($sql);
        //执行
        $stmt->execute();
        //清空查询条件
        $this->opt = [];
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    //添加数据
    public function insert(array $data) : int
    {
        $str = '';
        foreach ($data as $key => $value){
            $str .= $key .'= "'.$value.'", ';
        }
        $str = rtrim($str,', ');
        $sql = "INSERT $this->table SET $str;";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return  $stmt->rowCount();
    }
    //更新数据
    public function update(array $data)
    {
        $str = '';
        foreach ($data as $key => $value){
            $str .= $key .'= "'.$value.'", ';
        }
        $str = rtrim($str,', ');
        $sql = "UPDATE $this->table SET $str";
        $sql .= $this->opt['where'] ?? die('禁止无条件更新');
        $sql .= ";";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return  $stmt->rowCount();
    }
    //删除数据
    public function delete()
    {
        $sql = "DELETE FROM $this->table";
        $sql .= $this->opt['where'] ?? die('禁止无条件删除');
        $sql .= ";";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return  $stmt->rowCount();
    }
}